

import fs from "fs";
import axios from "axios";
export default class extends think.Service {
  /**
   * 获取token
   * @param config 小程序信息
   * @returns token
   */
  getAccessToken(config: WechatConfigFace): Promise<string> {
    const { app_id, secret } = config;
    return new Promise((resolve, reject) => {
      const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${app_id}&secret=${secret}`;
      axios.get(url).then((response) => {
        const data = response.data;
        const accessToken = data.access_token;
        resolve(accessToken);
      });
    });
  }

  
  /**
   * 根据code获取手机号
   * @param code
   * @param config
   * @returns
   */
  async getCodePhone(
    code: string,
    config: WechatConfigFace
  ): Promise<WechatPhoneInfoFace> {
    const accessToken = await this.getAccessToken(config);
    return new Promise((resolve, reject) => {
      const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
      const requestData = {
        code,
      };
      axios
        .post(url, requestData)
        .then((response) => {
          console.log(this)
          const data = response.data;
          if (data && data.errcode) {
            reject(data.errmsg);
          } else {
            resolve(data.phone_info);
          }
        })
        .catch((error) => {
          console.log("错误");
          console.error("Error:", error);
          reject();
        });
    });
  }
  /**
   * 根据code 获取Openid
   * @param code
   * @param config
   * @returns
   */
  async getOpenid(
    code: string,
    config: WechatConfigFace
  ): Promise<WechatJscodeInfoFace> {
    const accessToken = await this.getAccessToken(config);
    return new Promise((resolve, reject) => {
      const { app_id, secret } = config;
      const url = `https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&js_code=${code}&appid=${app_id}&secret=${secret}&access_token=${accessToken}`;
      const requestData = {
        code,
      };
      axios
        .post(url, requestData)
        .then((response) => {
          const data = response.data;
          console.log(data);
          if (data.errcode) {
            reject(data.errmsg);
            return;
          } else {
            resolve(data);
          }
        })
        .catch((error) => {
          console.log("错误");
          console.error("Error:", error);
          reject("获取失败");
          return;
        });
    });
  }

  async getWxaqrcode(config) {
    return new Promise(async (resolve, reject) => {
      const accessToken = await this.getAccessToken(config);
      const url = `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${accessToken}`;
      const requestData = {
        width: 430,
        path: "/pages/index/index",
      };

      axios({
        url: url,
        method: "post",
        data: requestData,
        timeout: 5000,
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
          responseType: 'arraybuffer'
        },
      })
        .then(async(response) => {
          const data = response.data;
          const length = data.length;
          console.log(Object.prototype.toString.call(data));
          const buffer = Buffer.from(data, 'utf-8');
          const base64Data = buffer.toString('base64');
          console.log(buffer);
          const datas = fs.writeFile("./a.png", buffer, (err) => {
            if (err) {
              reject();
              return;
            }
            resolve(data);
          });
        })
        .catch((error) => {
          console.log("错误");
          console.error("Error:", error);
          reject();
        });
    });
  }
}
